import React from 'react'

class CountDown extends React.Component {
  static timer = null

  // 没使用this, 要写成静态方法
  static format = (number) => {
    if (number < 10) return `0${number}`
    return number
  }

  constructor(props) {
    super(props)
    this.state = {
      seconds: props.startTimeStamp / 1000,
    }
  }

  componentDidMount() {
    const { onCountDownEnd } = this.props
    this.timer = setInterval(() => {
      this.setState(({ seconds }) => {
        if (seconds - 1 === 0) {
          clearInterval(this.timer)
          onCountDownEnd && onCountDownEnd()
        }
        return { seconds: seconds - 1 }
      })
    }, 1000)
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }

  render() {
    const { seconds } = this.state

    return (
      <span>
        {/* 时: */}
        {parseInt(seconds / 3600, 10) ? `${parseInt(seconds / 3600, 10)}:` : null}
        {/* 分: */}
        {`${this.format(parseInt((seconds % 3600) / 60, 10))}:`}
        {/* 秒 */}
        {`${this.format(parseInt(seconds % 60, 10))}`}
      </span>
    )
  }
}

export default CountDown
